//var userweb = "web";
// 模拟 plus 对象（非真机环境时）
if (typeof window.plus === 'undefined') {
	window.plus = {
		nativeUI: {
			showWaiting: function() {},
			closeWaiting: function() {}
		},
		navigator: {
			setStatusBarStyle: function() {}
		}
	};
}

// 标准 mui.plusReady 实现
mui.plusReady = function(callback) {
	if (window.plus && plus.isReady) {
		callback();
	} else {
		document.addEventListener('plusready', callback, false);
	}
};

var userweb = "app";
window.kos = {};
// http://192.168.137.1/		http://192.168.3.241:9005/


httpurl6 = httpurl5 = httpurl4 = httpurl3 = httpurl2 = httpurl1 = localStorage.getItem('ServerHttp');


//httpurl6 = httpurl5  = httpurl4 = httpurl3 = httpurl2 = httpurl1  = "http://192.168.137.1/";
/*function closeWindowThis() {
	try {
		//plus.webview.open('../index.html');
		plus.webview.currentWebview().close(); 
	} catch (e) {
		//TODO handle the exception
		window.location.href = "../index.html"; 
	}
}

function closeWindow() {
	try {
		//plus.webview.open('../index.html'); 
		plus.webview.currentWebview().close();
	} catch (e) {
		//TODO handle the exception
		window.location.href = "../index.html";
	}
}
   */

//同步请求 Get
function xccGet(urx, jsonc, call, err) {
	console.log(httpurl1 + urx + " 传参：" + JSON.stringify(jsonc));
	$.ajax({
		type: "GET", //传输方式
		url: httpurl1 + urx,
		data: jsonc,
		dataType: 'json',
		async: false, //是否异步请求
		success: function(data) {
			call(data);
		},
		error: function(xhr, textStatus, errorThrown) {
			//err(errorx);
			// 获取错误信息
			console.log(xhr.responseText);
			mui.toast("网络连接超时!!");
		}
	});
}

//Get
function xccpost(urx, jsonc, call, err) {
	console.log(httpurl1 + urx + " 传参：" + JSON.stringify(jsonc));
	$.ajax({
		type: "GET", //传输方式
		url: httpurl1 + urx,
		data: JSON.stringify(jsonc),
		// dataType: 'application/json; charset=utf-8',
		async: false, //是否异步请求
		success: function(data) {
			call(JSON.parse(data));
		},
		error: function(xhr, textStatus, errorThrown) {
			//err(errorx);
			// 获取错误信息
			console.log(xhr.responseText);
			mui.toast("Network connection timeout!!");
		}
	});
}
// post
function xccpostAsync(urx, jsonc, call, err) {
	console.log(httpurl1 + urx + " 传参：" + JSON.stringify(jsonc));
	//p判断是PC端	开启转圈圈特效
	if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
		plus.nativeUI.showWaiting();
		plus.navigator.setStatusBarStyle('dark');
	}
	$.ajax({
		type: "POST",
		url: httpurl1 + urx,
		data: JSON.stringify(jsonc),
		contentType: "application/json; charset=utf-8",
		dataType: 'json',
		crossDomain: true, // 明确声明跨域请求
		// xhrFields: {
		// 	withCredentials: true // 如果需要发送凭据(cookie等)
		// },
		headers: {
			'Accept': 'application/json',
			// 如果后端需要特定的自定义头，可以在这里添加
			// 'X-Requested-With': 'XMLHttpRequest'
		},
		success: function(data) {
			call(JSON.parse(data));
		},
		error: function(xhr, textStatus, errorThrown) {
			// 更详细的错误处理
			let errorMsg = "请求失败: ";
			if (xhr.status === 0) {
				errorMsg += "网络连接错误或跨域请求被阻止";
			} else if (xhr.status === 404) {
				errorMsg += "请求地址不存在";
			} else if (xhr.status === 500) {
				errorMsg += "服务器内部错误";
			} else if (xhr.status === 401) {
				errorMsg += "未授权，请登录";
			} else if (xhr.status === 403) {
				errorMsg += "禁止访问";
			} else {
				errorMsg += (xhr.responseText || textStatus || errorThrown);
			}
			//Audios();
			mui.toast(errorMsg);
			console.log(errorMsg);
			if (err) err(xhr, textStatus, errorThrown);
		}
	});
}

//异步表单提交请求
function xccFormPostAsync(urx, jsonc, call, err) {
	console.log(httpurl1 + urx + " 传参：" + JSON.stringify(jsonc));
	//p判断是PC端	开启转圈圈特效
	if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
		plus.nativeUI.showWaiting();
		plus.navigator.setStatusBarStyle('dark');
	}
	$.ajax({
		type: "POST", //传输方式
		url: httpurl1 + urx,
		data: jsonc,
		dataType: 'json',
		async: true, //是否异步请求
		contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
		success: function(data) {
			//p判断是PC端
			if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
				plus.nativeUI.closeWaiting(); //关闭转圈圈特效
			}
			call(JSON.parse(data));
		},
		error: function(errorx) {
			console.log(errorx.responseText);
			mui.toast("failed" + errorx.responseText, {
				duration: '1000',
				type: 'div'
			});
			//Audios();
			//p判断是PC端
			if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
				plus.nativeUI.closeWaiting(); //关闭转圈圈特效
			}
		}
	});
}

//异步表单提交请求
function xccGetAsync(urx, jsonc, call, err) {
	console.log(httpurl1 + urx + " 传参：" + JSON.stringify(jsonc));
	//p判断是PC端	开启转圈圈特效
	if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
		plus.nativeUI.showWaiting();
		plus.navigator.setStatusBarStyle('dark');
	}
	$.ajax({
		type: "GET", //传输方式
		url: httpurl1 + urx,
		data: jsonc,
		dataType: 'json',
		async: true, //是否异步请求
		success: function(data) {
			//p判断是PC端
			if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
				plus.nativeUI.closeWaiting(); //关闭转圈圈特效
			}
			call(data);
		},
		error: function(errorx) {
			err(errorx);
			mui.toast(errorx.responseText, {
				duration: '1000',
				type: 'div'
			});
			//Audios();
			//p判断是PC端
			if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
				plus.nativeUI.closeWaiting(); //关闭转圈圈特效
			}
		}
	});
}

//报警声音
function Audios() {
	var audio = new Audio('../../../fonts/baojin.mp3');
	audio.play();
}

function GetRequest() {
	var url = decodeURI(decodeURI(location.search)); //获取url中"?"符后的字串，使用了两次decodeRUI解码
	var theRequest = new Object();
	if (url.indexOf("?") != -1) {
		var str = url.substr(1);
		strs = str.split("&");
		for (var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
		}
		return theRequest;
	}
}

var Resquest = GetRequest();
var ResquestData;
if (Resquest) {
	if (Resquest.data != null) {
		ResquestData = JSON.parse(Base64.decode(Resquest.data));
	}
}

// config.js
mui.init({
	swipeBack: true // 移到这里统一配置
});
// mui.plusReady = function(call) {
// 	setTimeout(function() {
// 		call();
// 	}, 120);
// }

function initHtml(html, call) {
	var htms = html.replace(/-/g, "/");
	$.get("html/" + htms + ".html", function(result) {
		$("body").html(result);
		call();
	})

}



function goTabView(name, data, type) {

	if (userweb == "web") {
		var base = Base64.encode(JSON.stringify(data));

		window.location.href = "/html/index.html?data=" + base;
	} else {
		var time = 200,
			slider = "slide-in-right";

		if (type) {
			if (type.time) {
				time = type.time;
			}
			if (type.slider) {
				slider = type.slider;
			}
		}
		var base = Base64.encode(JSON.stringify(data));
		plus.webview.open("html/" + name + ".html?data=" + base, name, {}, slider, time);
		//plus.webview.open("page.html?fpm=" + name + "&data=" + base, name, {}, slider, time);
	}
}

function initjs(js) {
	var js1 = js.replace(/-/g, "/");
	var s = document.createElement("script");
	s.src = "js" + "/" + js1 + ".js";
	document.head.appendChild(s);

}
window.kos.page = function(page) {
	if (page == "page") {} else if (page == "index") {
		Resquest = {
			fpm: "index"
		};
	}
	mui.plusReady(function() {
		if (Resquest.fpm) {
			initHtml(Resquest.fpm, function() {
				initjs(Resquest.fpm);
				try {
					//判断是否支持沉浸式
					var isImmersedStatusbar = plus.navigator.isImmersedStatusbar();
					// console.log(isImmersedStatusbar);
					//获取系统状态栏高度
					var StatusbarHeight = plus.navigator.getStatusbarHeight();
					// console.log(StatusbarHeight);
					var headerH = h('.mui-bar-nav').eq(0).height();
					// console.log(headerH);
					h('.mui-bar-nav').eq(0).css({
						height: (headerH + StatusbarHeight) + 'px',
						'paddingTop': StatusbarHeight + 'px'
					});
					h('.mui-content').eq(0).css({
						paddingTop: (44 + StatusbarHeight) + 'px'
					});
					h('.searchMessage-box').eq(0).css({
						top: (44 + StatusbarHeight) + 'px'
					});

					// 消息和通讯录内容显示隐藏，以及搜索框的位置控制
					h(".btn-contacts").tap(function() {
						h(".message-box").css({
							"display": "none"
						});
						h(".contacts-box").css({
							"display": "block"
						});
						h('.contacts-box .searchMessage-box').eq(0).css({
							top: (44 + StatusbarHeight) + 'px'
						});
					});
				} catch (e) {
					//TODO handle the exception
				}
			});
		}
	});
}